//
//  LYRefreshControl.swift
//  微博
//
//  Created by liuerying on 16/5/27.
//  Copyright © 2016年 liuerying. All rights reserved.
//

import SnapKit

enum RefreshStatue {
    case Normal  //普通状态
    case Pulling  //准备刷新状态
    
    case Refreshing  //正在刷新
    
}

private let refreshViewHeight: CGFloat = 60

class LYRefreshControl: UIControl {

    var statue: RefreshStatue = .Normal{
    
        didSet{
        
            switch statue {
            case .Normal:
                
                arrowicon.hidden = false
                indicatorView.stopAnimating()
                tipLabel.text = "下拉起飞"
                
                UIView.animateWithDuration(0.25, animations: { 
                    self.arrowicon.transform = CGAffineTransformIdentity
                })
                
                if oldValue == .Refreshing{
                UIView.animateWithDuration(0.25, animations: { 
                    
                    
                    var inset = self.scrollView!.contentInset
                    
                    inset.top -= refreshViewHeight
                    
                    self.scrollView?.contentInset = inset
                    
                })
                
                    
                }
                
            case .Pulling:
                
                tipLabel.text = "准备起飞"
                UIView.animateWithDuration(0.25, animations: { 
                    self.arrowicon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing:
                
                arrowicon.hidden = true
                indicatorView.startAnimating()
                
                tipLabel.text = "正在刷新"
                
                //请求网络数据 给观察的对象主动发送对应类型的事件
                sendActionsForControlEvents(.ValueChanged)
          
           UIView.animateWithDuration(0.25, animations: { 
            
            
               var inset = self.scrollView!.contentInset
            
               inset.top += refreshViewHeight
            
               self.scrollView?.contentInset = inset
           })
          
            }
            
        }
        
      
        
        
        }
    
      func endRefreshing(){
        statue = .Normal
    }
    
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refreshViewHeight, width: ScreeWidth, height: refreshViewHeight)
        super.init(frame: rect)
        backgroundColor = UIColor.yellowColor()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //键值观察的响应方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let offsety = scrollView?.contentOffset.y ?? 0
        
        //如果有被拖拽
        if scrollView!.dragging{
        
            if statue == .Pulling && offsety > -124{
            
                statue = .Normal
                
            }else if statue == .Normal && offsety < -124{
            
                statue = .Pulling
            }
            
        }else{
        
            if statue == .Pulling{
            
                statue = .Refreshing
            }
        }
    }

    //将要移动到父视图上
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        
        //获取tableView
        if let myFather = newSuperview as? UIScrollView{
        
            scrollView = myFather
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
            
        }
    }
    
    
    private func setupUI(){
        //下拉刷新背景图片
        addSubview(backImageView)
        //箭头
        addSubview(arrowicon)
        //文字
        addSubview(tipLabel)
        //小菊花
        addSubview(indicatorView)
        
        //设置约束
        backImageView.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self)
        }
        
        arrowicon.snp_makeConstraints { (make) in
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        tipLabel.snp_makeConstraints { (make) in
            make.left.equalTo(arrowicon.snp_right)
            make.centerY.equalTo(self.snp_centerY)
        }
        
        indicatorView.snp_makeConstraints { (make) in
            make.center.equalTo(arrowicon.snp_center)
        }
    
    }
    
    var scrollView : UIScrollView?
    //添加下拉刷新背景图片
    private lazy var backImageView : UIImageView = UIImageView(image: UIImage(named: "refreshbg"))
    
   
    //箭头
    private lazy var arrowicon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    private lazy var tipLabel:UILabel = UILabel(title: "下拉起飞", font: 14, textcolor: UIColor.darkGrayColor())
    
    private lazy var indicatorView:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    
    
    deinit{
    
        //移除键值观察值
        scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
